// import axios from 'axios'
import React, { useEffect, useState, useRef } from 'react'
import { Button, Space,Toast } from 'antd-mobile'
import { Form, Input } from 'antd-mobile'
import img1 from "../imgs/10.jpg"
import style from "../login/Login.module.css"
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import { sendVerificationCode,verifyVerificationCode } from '../http/api'
import { UserOutline, UnlockOutline } from 'antd-mobile-icons'
import SliderCaptcha from 'rc-slider-captcha';
import { RubyOutlined, MehOutlined, SmileOutlined, RedoOutlined, LoadingOutlined } from '@ant-design/icons' //引入antd的图标组件
import { sleep } from 'ut2'; //引入sleep函数，用于模拟延迟
import createPuzzle from 'create-puzzle';
import axios from 'axios'
import { useNavigate } from 'react-router-dom'
export default function Login() {
  const [user, setuser] = useState([])
  const [phone, setphone] = useState("")
  const [zhanghao, setzhanghao] = useState("")
  const [password, setpassword] = useState("")
  const [yzm, setyzm] = useState("")
  const [visible, setVisible] = useState(false)
  const [qiehuan, setqiehuan] = useState(false)
  const [youxiang,setyouxiang]=useState()
    const [countdown, setCountdown] = useState(0)
    const [currentStep, setCurrentStep] = useState(0);
  const navigate = useNavigate()
  const shoulogin = () => {
    setqiehuan(false)
  }
  const zhanglogin = () => {
    setqiehuan(true)
  }

  const getuser = () => {
    axios.post("http://localhost:3111/user/getuser", { phone: phone, zhanghao: zhanghao, password: password,youxiang:youxiang }).then(res => {
      if (res.data.code === 200) {
        setuser(res.data.data)
        localStorage.setItem("user", JSON.stringify(res.data.data))
        if(youxiang){
          handleVerifyCode()
        }else{
          navigate("/zhu")
        }
      } else {
        alert("cuowu")
      }
    })
  }
  // console.log(user);



  // useEffect(()=>{
  //   getuser()
  // },[])

  const login = () => {
    getuser()
  }
  // console.log(phone);


  const offsetXRef = useRef(0); // 用于存储拼图块的正确位置
  const [pintu, setpintu] = useState(false)

  const verifyCaptcha = async (data) => {
    await sleep();   //模拟网络延迟请求
    // 判断用户拖动的位置是否在正确位置5px偏移量内
    if (data.x >= offsetXRef.current - 5 && data.x < offsetXRef.current + 5) {
      // 延迟1秒后调用成功回调函数
      setTimeout(() => {
        // params?.onSuccess() //调用父组件传递的成功回调函数
      }, 1000)
      return setTimeout(() => {
        setpintu(false)
        handleSendCode()
        // params?.onSuccess() //调用父组件传递的成功回调函数
      }, 1000); //验证成功
    }
    return Promise.reject(); //验证失败
  };


// const [form] = Form.useForm();
  const handleSendCode = async () => {
    const email = youxiang;
    if (!email) {
      Toast.show({
        content: '请输入邮箱',
        position: 'center',
      });
      return;
    }
    try {
      const result = await sendVerificationCode(email);
      if (result.code === 200) {
        Toast.show({
          content: '验证码已发送',
          position: 'center',
        });
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown(prevCount => {
            const newCount = prevCount - 1;
            if (newCount <= 0) {
              clearInterval(timer);
            }
            return newCount;
          });
        }, 1000);
      } else {
        Toast.show({
          content: result.message,
          position: 'center',
        });
      }
    } catch (error) {
      console.error('发送验证码出错:', error);
      Toast.show({
        content: '发送验证码失败，请稍后重试',
        position: 'center',
      });
    }
  };

   // 验证验证码
    const handleVerifyCode = async () => {
        // const { email, captcha } = form.getFieldsValue();
        const email=youxiang
        const captcha=yzm

        if (!email || !captcha) {
            Toast.show({
                content: '请输入邮箱和验证码',
                position: 'center',
            });
            return;
        }
        try {
            const result = await verifyVerificationCode(email,captcha);
            if (result.code === 200) {
                Toast.show({
                    content: '验证成功',
                    position: 'center',
                });
                // setToken(result.data.token);
                setCurrentStep(2);
                navigate(`/zhu`)
            } else {
                Toast.show({
                    content: result.message,
                    position: 'center',
                });
            }
        } catch (error) {
            console.error('验证验证码出错:', error);
            Toast.show({
                content: '验证验证码失败，请稍后重试',
                position: 'center',
            });
        }
    };



  return (
    <div>
      <div className={style.logo}><img src={img1} alt="" className={style.img1} /></div>
      <h1 className={style.shi}>十六OA考勤</h1>

      <div className={style.login}>
        <div style={{ display: qiehuan ? "none" : "" }}>
          <Form layout='horizontal'>
            <Form.Item label='邮箱号：' name='username'>
              <Input placeholder='请输入邮箱号' clearable value={youxiang} onChange={(e) => { setyouxiang(e) }} />
            </Form.Item>


            <Form.Item
              label='验证码：'
              extra={
                <div className={style.extraPart}>
                  <a 
                    className={style.yzm} 
                    onClick={() => { countdown === 0 && setpintu(true) }}
                    style={{ 
                      color: countdown > 0 ? '#999' : '#1677ff',
                      cursor: countdown > 0 ? 'not-allowed' : 'pointer'
                    }}
                  >
                    {countdown > 0 ? `${countdown}秒后重试` : '发送验证码'}
                  </a>
                </div>
              }
            >
              <Input placeholder='请输入验证码' clearable value={yzm} onChange={(e) => { setyzm(e) }} />
            </Form.Item>
          </Form>
        </div>

        <div style={{ display: qiehuan ? "" : "none" }}>
          <Form layout='horizontal'>
            <Form.Item label={<div><UserOutline /> 账号</div>} name='username'>
              <Input placeholder='请输入账号' clearable value={zhanghao} onChange={(e) => { setzhanghao(e) }} />
            </Form.Item>
            <Form.Item
              label={<div><UnlockOutline /> 密码</div>}
              name='password'
              extra={
                <div className={style.eye}>
                  {!visible ? (
                    <EyeInvisibleOutline onClick={() => setVisible(true)} />
                  ) : (
                    <EyeOutline onClick={() => setVisible(false)} />
                  )}
                </div>
              }
            >
              <Input
                placeholder='请输入密码'
                clearable
                type={visible ? 'text' : 'password'}
                value={password} onChange={(e) => { setpassword(e) }}
              />
            </Form.Item>
          </Form>
        </div>


        <div className={style.dengbut}>
          <Button block color='primary' size='large' onClick={() => { login() }}>
            登录
          </Button>
          <p className={style.qiehuan}><span>忘记密码？</span> {qiehuan ? <span onClick={shoulogin}>手机号登录</span> : <span onClick={zhanglogin}>账号登录</span>}</p>
        </div>

      </div>

      <div style={{ display: pintu ? "" : "none" }} className={style.pintu}>
        <SliderCaptcha
          request={() =>
            createPuzzle("https://picsum.photos/300/150", {
              format: 'blob' //指定输出格式为二进制数据流
            }).then((res) => {
              offsetXRef.current = res.x //保存拼图块的正确位置
              return {
                // 背景图片
                bgUrl: res.bgUrl, //背景图地址
                // 核验区域
                puzzleUrl: res.puzzleUrl
              };
            })
          }
          onVerify={(data) => {
            return verifyCaptcha(data);
          }}
          // ！！！！这里是重点！！！！！
          // bgSize必须和原图片的尺寸一样！！！！！！！！！！！！！！！！！！
          bgSize={{ width: 300, height: 150 }}
          tipIcon={{
            default: <RubyOutlined />,
            loading: <LoadingOutlined />,
            success: <SmileOutlined />,
            error: <MehOutlined />,
            refresh: <RedoOutlined />
          }}
          tipText={{
            default: '向右👉拖动完成拼图',
            loading: '👩🏻‍💻🧑‍💻努力中...',
            moving: '向右拖动至拼图位置',
            verifying: '验证中...',
            error: '验证失败',
            success: '验证成功'
          }}
        />
      </div>
    </div>
  )
}
